import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Component, OnInit, Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { RestService } from './../services/rest.service';
import { LoginService } from './../services/login.service';
import { Subscription } from 'rxjs/Rx';

import * as _ from 'lodash';

@Component({
  styleUrls: ['./login.component.css'],
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  loginInProgress = false;

  constructor(private fb: FormBuilder,
              private router: Router,
              private restService: RestService,
              private loginService: LoginService) {
    this.loginForm = fb.group({
      userName: [
        '',
        [
          Validators.required,
          Validators.minLength(4)
        ]
      ],
      userPassword: [
        '',
        [
          Validators.required,
          Validators.minLength(4)
        ]
      ]
    });
  }

  private loginSuccess(loginInfo, data): void {
    this.loginInProgress = false;
    this.restService.saveUser({
      name: data.userName,
      role: loginInfo.role
    });

    this.restService.saveEnCred(btoa(data.userName + ':' + data.userPassword));

    this.go2DefaultModule();
  }

  private loginFail(error, data): void {
    this.loginInProgress = false;
    this.restService.openErrorDialog('登录失败！');
  }

  private go2DefaultModule() {
    this.router.navigateByUrl('/home/trains');
  }

  login(data): void {
    this.loginInProgress = true;
    if (this.restService.isDebugging()) {
      this.go2DefaultModule();
      return;
    }

    // clean up local storage before login
    this.restService.cleanupLocalStorage();

    this.restService.saveUser({
      name: data.userName,
      role: ''
    });

    this.restService.login(data).subscribe(
      loginInfo => this.loginSuccess(loginInfo, data),
      error => this.loginFail(error, data));
  }

  onSubmit(event) {
    const userName$ = this.loginForm.controls['userName'];
    const userPassword$ = this.loginForm.controls['userPassword'];
    this.login({
      userName: userName$.value,
      userPassword: userPassword$.value
    });
  }

  ngOnInit() {
    this.loginInProgress = false;
  }
}
